import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Table, Button, Modal, Form, Input, Select, Space, message, Popconfirm, Spin, Alert } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import api from '../../services/api';
import socketService from '../../services/socket';

const { Option } = Select;

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deletingUserId, setDeletingUserId] = useState(null);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [fetchError, setFetchError] = useState(null);
  const [loadingTooLong, setLoadingTooLong] = useState(false);
  
  // 引用标记当前组件是否已卸载，防止内存泄漏
  const isMounted = useRef(true);
  // 用于跟踪加载时间和取消请求
  const loadingTimer = useRef(null);
  const abortController = useRef(new AbortController());

  // 组件挂载时暂停WebSocket自动重连
  useEffect(() => {
    // 添加一个标记，防止重复处理同一个组件实例
    const componentId = Date.now();
    isMounted.current = true;
    console.log(`进入用户管理页面 [${componentId}]，暂停WebSocket自动重连`);
    socketService.pauseReconnect();
    
    // 在组件挂载时获取用户列表
    fetchUsers();
    
    // 清理函数，组件卸载时调用
    return () => {
      // 只有当组件真正卸载时才执行清理操作
      if (isMounted.current) {
        isMounted.current = false;
        console.log(`离开用户管理页面 [${componentId}]，恢复WebSocket自动重连`);
        socketService.resumeReconnect();
        
        // 清理定时器和取消请求
        if (loadingTimer.current) {
          clearTimeout(loadingTimer.current);
          loadingTimer.current = null;
        }
        
        // 确保只在组件真正卸载时才取消请求
        if (abortController.current) {
          console.log(`[${componentId}] 组件卸载，取消未完成的请求`);
          abortController.current.abort('组件卸载');
          abortController.current = null;
        }
      }
    };
  }, []);

  const fetchUsers = async () => {
    if (!isMounted.current) return;
    
    // 检查是否有登录令牌
    const token = localStorage.getItem('token');
    if (!token) {
      if (isMounted.current) {
        setFetchError('您尚未登录或登录已过期，请重新登录');
        message.error('请先登录');
        // 重定向到登录页面
        setTimeout(() => {
          window.location.href = '/login';
        }, 2000);
      }
      return;
    }
    
    // 重置状态
    setLoading(true);
    setFetchError(null);
    setLoadingTooLong(false);
    
    // 如果有进行中的请求，取消它
    if (abortController.current) {
      abortController.current.abort();
    }
    abortController.current = new AbortController();
    
    // 设置加载时间过长检测
    if (loadingTimer.current) {
      clearTimeout(loadingTimer.current);
    }
    
    loadingTimer.current = setTimeout(() => {
      if (isMounted.current && loading) {
        setLoadingTooLong(true);
      }
    }, 5000);
    
    try {
      console.log('开始获取用户列表...');
      // 使用新的AbortController发送请求
      const response = await api.get('/admin/users', { 
        timeout: 10000,
        signal: abortController.current.signal
      });
      
      if (isMounted.current) {
        if (response.data && Array.isArray(response.data)) {
          console.log(`成功获取${response.data.length}个用户`);
          setUsers(response.data);
        } else {
          console.warn('获取用户列表返回格式不正确', response.data);
          setUsers([]);
        }
      }
    } catch (error) {
      // 忽略被取消的请求错误
      if (error.name === 'CanceledError' || error.name === 'AbortError') {
        console.log('请求已取消，这通常是由于组件卸载或用户触发了新请求');
        return;
      }
      
      console.error('获取用户列表失败:', error);
      if (isMounted.current) {
        // 判断是否为认证错误
        const isAuthError = error.response?.status === 401 || error.response?.status === 403;
        // 判断是否为CORS错误
        const isCorsError = error.message === 'Network Error' || 
                        (error.response?.status === 0) || 
                        error.code === 'ERR_NETWORK';
        
        const isServerDown = !error.response && (error.code === 'ERR_NETWORK' || error.message === 'Network Error');
        
        if (isAuthError) {
          setFetchError('认证失败，请重新登录');
          // 清除无效令牌
          localStorage.removeItem('token');
          // 延迟重定向到登录页面
          setTimeout(() => {
            window.location.href = '/login';
          }, 2000);
        } else if (isCorsError) {
          setFetchError('跨域请求被阻止，请检查后端CORS配置是否正确');
        } else if (isServerDown) {
          setFetchError('无法连接到服务器，请确认后端服务是否已启动');
        } else {
          setFetchError(error.response?.data?.message || error.message || '获取用户数据失败');
        }
      }
    } finally {
      if (isMounted.current) {
        setLoading(false);
        if (loadingTimer.current) {
          clearTimeout(loadingTimer.current);
          loadingTimer.current = null;
        }
      }
    }
  };

  const showAddModal = useCallback(() => {
    setEditingId(null);
    setModalVisible(true);
    // 延迟重置字段，确保Modal完全渲染后再重置
    setTimeout(() => {
      form.resetFields();
    }, 0);
  }, [form]);

  const showEditModal = useCallback((record) => {
    setEditingId(record.id);
    setModalVisible(true);
    // 延迟设置字段值，确保Modal完全渲染后再设置
    setTimeout(() => {
      form.setFieldsValue({
        username: record.username,
        fullName: record.fullName,
        email: record.email,
        role: record.role,
        status: record.status,
      });
    }, 0);
  }, [form]);

  const handleCancel = useCallback(() => {
    setModalVisible(false);
    // 确保模态框关闭后重置表单
    setTimeout(() => {
      form.resetFields();
    }, 100);
  }, [form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitLoading(true);
      
      if (editingId) {
        // 更新现有用户 - 使用PATCH方法
        await api.patch(`/admin/users/${editingId}`, values);
        message.success('用户更新成功');
      } else {
        // 创建新用户
        await api.post('/admin/users', values);
        message.success('用户创建成功');
      }
      
      setModalVisible(false);
      
      // 添加延迟，避免服务器端处理时间差导致数据不一致
      setTimeout(() => {
        if (isMounted.current) {
          fetchUsers();
        }
      }, 500);
    } catch (error) {
      if (error.name !== 'AbortError') {
        const errorMsg = error.response?.data?.message || '操作失败';
        message.error(editingId ? `更新用户失败: ${errorMsg}` : `创建用户失败: ${errorMsg}`);
        console.error('提交表单失败:', error);
      }
    } finally {
      if (isMounted.current) {
        setSubmitLoading(false);
      }
    }
  };

  // 直接删除用户不经过服务器查询
  const handleDeleteDirectly = async (id, username) => {
    try {
      setDeleteLoading(true);
      setDeletingUserId(id);
      console.log(`开始直接删除用户ID: ${id}, 用户名: ${username}`);
      
      // 添加请求拦截器，只针对这一次请求
      const originalRequest = api.interceptors.request.use((config) => {
        console.log('删除请求配置:', {
          url: config.url,
          method: config.method,
          headers: config.headers
        });
        return config;
      });
      
      // 添加响应拦截器，只针对这一次请求
      const originalResponse = api.interceptors.response.use(
        (response) => {
          console.log('删除成功响应:', {
            status: response.status,
            data: response.data
          });
          return response;
        },
        (error) => {
          console.log('删除错误响应:', {
            status: error.response?.status,
            data: error.response?.data,
            message: error.message
          });
          return Promise.reject(error);
        }
      );
      
      try {
        const response = await api.delete(`/admin/users/${id}`);
        
        // 移除临时添加的拦截器
        api.interceptors.request.eject(originalRequest);
        api.interceptors.response.eject(originalResponse);
        
        console.log('删除用户响应:', response.data);
        
        message.success(`用户 ${username} 删除成功`);
        
        // 直接从本地状态中删除用户
        setUsers(prevUsers => prevUsers.filter(user => user.id !== id));
      } catch (error) {
        // 移除临时添加的拦截器
        api.interceptors.request.eject(originalRequest);
        api.interceptors.response.eject(originalResponse);
        
        throw error; // 继续抛出错误以便后续处理
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      console.error('错误详情:', {
        status: error.response?.status,
        message: error.response?.data?.message,
        stack: error.stack
      });
      
      if (error.response && error.response.data && error.response.data.message) {
        message.error(`删除用户失败: ${error.response.data.message}`);
      } else {
        message.error('删除用户失败，请检查网络连接或联系管理员');
      }
    } finally {
      if (isMounted.current) {
        setDeleteLoading(false);
        setDeletingUserId(null);
      }
    }
  };

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'fullName',
      key: 'fullName',
      render: (text) => text || '未设置',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      render: (text) => text || '未设置',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => (
        <span>{role === 'admin' ? '管理员' : '销售人员'}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 'active' ? 'green' : 'red' }}>
          {status === 'active' ? '活跃' : '禁用'}
        </span>
      ),
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginAt',
      key: 'lastLoginAt',
      render: (lastLoginAt) => lastLoginAt ? new Date(lastLoginAt).toLocaleString() : '未登录',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        // 获取当前用户ID并进行类型转换
        const currentUserIdStr = localStorage.getItem('userId');
        const currentUserId = currentUserIdStr ? Number(currentUserIdStr) : null;
        const recordId = Number(record.id);
        
        // 调试信息
        console.log('删除按钮渲染:', {
          currentUserIdStr,
          currentUserId,
          recordId,
          recordRole: record.role,
          isCurrentUser: currentUserId === recordId,
          isAdmin: record.role === 'admin'
        });
        
        // 正确的禁用条件
        const isDisabled = record.role === 'admin' || currentUserId === recordId;
        
        // 直接删除函数（临时解决方案）
        const handleDirectDelete = () => {
          console.log('🔥 删除按钮被点击!', { recordId: record.id, username: record.username });
          
          // 手动确认
          const confirmed = window.confirm(`确定要删除用户 ${record.username} 吗？`);
          if (confirmed) {
            console.log('✅ 用户确认删除');
            handleDeleteDirectly(record.id, record.username);
          } else {
            console.log('❌ 用户取消删除');
          }
        };
        
        return (
          <Space size="middle">
            <Button 
              type="primary" 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => showEditModal(record)}
            >
              编辑
            </Button>
            <Popconfirm
              title={`确定要删除用户 ${record.username} 吗?`}
              onConfirm={() => {
                console.log('🔥 Popconfirm触发删除!', { recordId: record.id, username: record.username });
                handleDeleteDirectly(record.id, record.username);
              }}
              okText="确定"
              cancelText="取消"
              onCancel={() => console.log('❌ Popconfirm取消删除')}
            >
              <Button 
                type="primary" 
                danger 
                icon={<DeleteOutlined />} 
                size="small"
                loading={deleteLoading && deletingUserId === record.id}
                disabled={isDisabled}
                onClick={(e) => {
                  console.log('🔥 删除按钮原生点击事件!', { recordId: record.id, username: record.username });
                  // 如果Popconfirm不工作，使用备用方案
                  if (!isDisabled) {
                    console.log('🔧 检测到按钮可用，3秒后触发备用删除方案...');
                    setTimeout(() => {
                      if (window.confirm(`Popconfirm似乎不工作。是否使用备用方案删除用户 ${record.username}？`)) {
                        handleDeleteDirectly(record.id, record.username);
                      }
                    }, 3000);
                  }
                }}
                title={isDisabled ? 
                  (record.role === 'admin' ? '不能删除管理员' : '不能删除当前登录用户') : 
                  '点击删除用户 - 如果Popconfirm不显示，3秒后会提供备用方案'
                }
              >
                删除
              </Button>
            </Popconfirm>
            
            {/* 临时的直接删除按钮 */}
            {!isDisabled && (
              <Button 
                type="link" 
                danger 
                size="small"
                onClick={handleDirectDelete}
                style={{ fontSize: '12px', padding: '0 4px' }}
              >
                [直接删除]
              </Button>
            )}
          </Space>
        );
      },
    },
  ];

  // 如果出现错误，显示错误信息和重试按钮
  if (fetchError) {
    return (
      <div style={{ textAlign: 'center', margin: '50px auto' }}>
        <h3 style={{ color: '#f5222d' }}>加载用户数据时出错</h3>
        <Alert
          message={fetchError}
          type="error"
          style={{ maxWidth: '500px', margin: '0 auto 20px' }}
          showIcon
        />
        <p style={{ marginBottom: '20px' }}>可能的解决方法：</p>
        <ul style={{ textAlign: 'left', maxWidth: '400px', margin: '0 auto 20px', listStylePosition: 'inside' }}>
          <li>确认后端服务已启动</li>
          <li>检查网络连接</li>
          <li>验证用户是否有权限访问</li>
        </ul>
        <Button 
          type="primary" 
          icon={<ReloadOutlined />} 
          onClick={fetchUsers} 
          style={{ marginTop: 16 }}
        >
          重新加载
        </Button>
      </div>
    );
  }

  return (
    <div className="user-management-container">
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2 style={{ margin: 0 }}>用户管理</h2>
        <Space>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={fetchUsers}
            loading={loading}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={showAddModal}
          >
            添加用户
          </Button>
        </Space>
      </div>

      {loadingTooLong && loading && (
        <Alert
          message="加载时间较长"
          description="用户数据加载时间超过预期，请耐心等待或尝试刷新页面。如问题持续，请检查后端服务状态。"
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      <Table 
        columns={columns} 
        dataSource={users} 
        rowKey="id" 
        loading={loading}
        pagination={{ 
          pageSize: 10,
          hideOnSinglePage: true,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
        locale={{ 
          emptyText: loading ? (
            <div style={{ padding: '20px 0' }}>
              <Spin spinning={true} tip="加载中..." />
            </div>
          ) : '暂无用户数据' 
        }}
      />

      <Modal
        title={editingId ? "编辑用户" : "添加用户"}
        open={modalVisible}
        onCancel={handleCancel}
        onOk={handleSubmit}
        confirmLoading={submitLoading}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          name="userForm"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          
          {!editingId && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="密码" />
            </Form.Item>
          )}
          
          <Form.Item
            name="fullName"
            label="姓名"
          >
            <Input placeholder="姓名" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}
          >
            <Input prefix={<MailOutlined />} placeholder="邮箱" />
          </Form.Item>
          
          <Form.Item
            name="role"
            label="角色"
            initialValue="sales"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="选择角色">
              <Option value="admin">管理员</Option>
              <Option value="sales">销售人员</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
            initialValue="active"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="选择状态">
              <Option value="active">活跃</Option>
              <Option value="disabled">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement; 